package sobchak.tools;

import sobchak.ITajik;
import sobchak.NashaRashaTajik;
import sobchak.Parameters;
import sobchak.event.EventProcessor;
import sobchak.event.EventProducer;
import sobchak.tools.exception.TajikAlreadyInRoomException;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 04.03.2010
 * Time: 16:47:25
 * To change this template use File | Settings | File Templates.
 */
public final class Room extends EventProducer {


	private static Room room_inst = new Room();


	public static Room getActiveRoom() {
		return room_inst;
	}

	public final CementBuilder cement_builder = new CementBuilder();
	public CementTank active_cement_tank;
	public final Wall rawshan_wall = Wall.buildWall();
	public final Wall djamshut_wall = Wall.buildWall();

	public final NashaRashaTajik rawsan = new NashaRashaTajik(NashaRashaTajik.RAWSHAN, rawshan_wall);
	public final NashaRashaTajik djamshut = new NashaRashaTajik(NashaRashaTajik.DJUMSHUT, djamshut_wall);
	private AtomicInteger brick_build = new AtomicInteger();


	Room() {
		EventProcessor.buildEventProcessor().setRoom(this);
	}

	public ITajik meetRawshan() {
        onTajikMeetIntoRoom(rawsan);
		return rawsan;
	}

	public ITajik meetDjamShut() {
        onTajikMeetIntoRoom(djamshut);
		return djamshut;
	}

    private void onTajikMeetIntoRoom(NashaRashaTajik ajik) {
        if(ajik.isTajikInRoom())
            throw new TajikAlreadyInRoomException(ajik);
        ajik.meetTajikInRomm();
    }

	public CementBuilder getBuilder() {
		return cement_builder;
	}

	public void setActiveCementTank(CementTank tank) {
		if(tank.isActive()) {
			listener.onEvent(this, Events.ACTIVATE_ACTIVE_CEMENT_TANK);
			return;
		}

		if(System.currentTimeMillis()-tank.getBuildTime() > Parameters.CEMENT_BUILDING_WAIT_TIME) {
			listener.onEvent(this, Events.CEMENT_TANK_TO_OLD);
			return;
		}

		tank.activate();
		if(active_cement_tank != null)
			active_cement_tank.activate();
		active_cement_tank = tank;

	}

	public int getBrickBuildCount() {
		return brick_build.get();
	}

	public Brick getBrick(ITajik tajik) {
		brick_build.incrementAndGet();
		return new Brick(tajik);
	}


}
